package com.qingmeng.applyjob.portal.config;

import com.qingmeng.applyjob.mapper.UserMapper;
import com.qingmeng.applyjob.model.User;
import com.qingmeng.applyjob.model.UserExample;
import com.qingmeng.applyjob.portal.bo.PortalUserDetails;
import com.qingmeng.applyjob.portal.service.UserService;
import com.qingmeng.applyjob.security.component.DynamicSecurityService;
import com.qingmeng.applyjob.security.config.SecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * portal-security模块相关配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class PortalSecurityConfig extends SecurityConfig {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                UserExample example = new UserExample();
                example.createCriteria().andUsernameEqualTo(s);
                List<User> users = userMapper.selectByExample(example);
                if (!CollectionUtils.isEmpty(users)) {
                    User user = users.get(0);
                    return new PortalUserDetails(user);
                }
                throw new UsernameNotFoundException("用户不存在");
            }
        };
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers(
                "/static/**",
                "/favicon.ico",
                "/error",
                "/index.html",
                "/uploads/**");
    }
}
